//import { io } from "socket.io-client";
import io from '@/common/uni-socket.io.js';
import { staticUrl } from '@/config.js';
export default {
  socket: null,
  onSocket(query) {
    //每次建立长连接之前先断开连接，防止重复
    if (this.socket) {
      this.socket.close();
    }
    //http://192.168.7.12:8699
    this.socket = io(staticUrl, {
      query,
      transports: ['websocket', 'xhr-polling', 'jsonp-polling'],
      timeout: 5000,
    });
    // 监听连接
    this.socket.on('connect', () => {
      console.log('socket已连接');
    });
    // 监听失败
    this.socket.on('error', () => {
      console.log('socket连接失败');
      removeListener();
      this.socket = null;
      //监听失败时，可以再次调用监听事件
    });
    // 连接错误
    this.socket.on('connect_error', (d) => {
      console.log('socket连接失败', d);
      removeListener();
      this.socket = null;
    });
    // 连接超时
    this.socket.on('connect_timeout', (d) => {
      console.log('socket连接超时', d);
      this.socket = null;
    });
    // 断开连接
    this.socket.on('disconnect', (reason) => {
      console.log('socket断开连接', reason);
      removeListener();
      this.socket = null;
    });
    // 重新连接
    this.socket.on('reconnect', (attemptNumber) => {
      console.log('socket成功重连', attemptNumber);
    });
    // 移除监听事件
    const removeListener = () => {
      if (this.socket) {
        this.socket.removeListener(); //一般用不到
      }
    };
  },
  closeSocket() {
    if (this.socket) {
      this.socket.close();
      this.socket = null;
    }
  },
};
